const express = require('express')
const cors = require('cors')
const db = require('./config/database')

const app = express()

// 中间件
app.use(cors())
app.use(express.json())

// 健康检查
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() })
})

// 小说列表API
app.get('/api/novels', async (req, res) => {
  try {
    console.log('收到小说列表请求')

    // 查询小说信息
    const novels = await db.query(`
      SELECT 
        id,
        title,
        author,
        description,
        cover_url,
        category,
        tags,
        status,
        word_count,
        chapter_count,
        rating,
        view_count,
        like_count,
        is_vip,
        created_at,
        updated_at
      FROM novels
      ORDER BY updated_at DESC
      LIMIT 10
    `)

    console.log('查询到小说数量:', novels.length)

    res.json({
      success: true,
      data: novels,
      message: `获取到 ${novels.length} 部小说`
    })
  } catch (error) {
    console.error('获取小说列表失败:', error)
    res.status(500).json({
      success: false,
      message: '获取小说列表失败',
      error: error.message
    })
  }
})

// 启动服务器
const PORT = 3001
app.listen(PORT, () => {
  console.log(`🚀 简单服务器启动成功！`)
  console.log(`📍 地址: http://localhost:${PORT}`)
  console.log(`🔍 健康检查: http://localhost:${PORT}/health`)
  console.log(`📚 小说API: http://localhost:${PORT}/api/novels`)
})
